import io
import random

import os
import string
import uuid

import time
from PIL import Image, ImageDraw, ImageFont
from django.core.paginator import Paginator
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse

from App.models import User, Home, Content, ConStyle
from myChat.settings import BASE_DIR

# 主页
def index(request):
    wheels=Home.objects.all()
    utoken = request.COOKIES.get('utoken', None)
    conStyl=ConStyle.objects.all()

    if utoken:
        uname = User.objects.filter(utoken=utoken).first().uname
        data = {
                'imgs': wheels,
                'conStyl':conStyl,
                'uname':uname
              }
        return render(request, 'home.html', context=data)
    else:
        data={
            'imgs':wheels,
            'conStyl': conStyl,
            'uname':'登录',
        }
        return render(request, 'home.html', context=data)


# 注册页面
def register(request):
    utoken = request.COOKIES.get('utoken', None)
    if request.method=='GET':
        con_style = ConStyle.objects.all()
        if utoken:
            uname=User.objects.filter(utoken=utoken).first().uname
            data = {
                'con_style': con_style,
                'utoken':utoken,
                'uname':uname
            }
            return render(request,'register.html',context=data)
        else:
            data = {
                'con_style': con_style,
                'utoken': utoken,
                'uname': '登录'
            }
            return render(request, 'register.html', context=data)

    else:

        uname=request.POST.get('uname',None)
        upwd=request.POST.get('upwd',None)
        ucode=request.POST.get('ucode',None)
        uicon=request.FILES.get('uicon',None)
        sessucode=request.session.get('vcode',None)
        item=User.objects.filter(uname=uname)
        if uname and upwd and ucode.lower()==sessucode.lower() and not item:
            user=User()
            user.uname=uname
            user.upwd=upwd
            user.uicon=uicon
            user.ucode=ucode
            user.save()
            if utoken:
                res=HttpResponseRedirect('/')
                return res
            else:
                return redirect(reverse('app:login'))
        else:
            return redirect(reverse('app:register'))

# 生成验证码
def getvcode(request):
    position=string.ascii_letters+string.digits
    vcode=''.join(random.sample(position,4))

    # 保存验证码
    request.session['vcode']=vcode
    # 生成画布
    image=Image.new('RGB',(150,50),color=getrandomcolor())
    # 创建画笔
    draw=ImageDraw.Draw(image)
    # 生成验证码
    path=os.path.join(BASE_DIR,'static','fonts','ADOBEARABIC-BOLD.OTF')
    font=ImageFont.truetype(font=path,size=50)
    for i in range(len(vcode)):
     draw.text((15+30*i,2),vcode[i],fill=getrandomcolor(),font=font)
    # 生成噪声（500个不同颜色的点）：
    for i in range(500):
        positions = (random.randint(0, 150), random.randint(0, 50))
        draw.point(positions,fill=getrandomcolor())
    # 创建字节容器
    buffer=io.BytesIO()
    # 将画布丢入容器
    image.save(buffer,'png')

    return HttpResponse(buffer.getvalue(),'image/png')

# 生成随机三种颜色的rgb值
def getrandomcolor():
    red=random.randint(0,255)
    green = random.randint(0, 255)
    black = random.randint(0, 255)
    return (red,green,black)


# 登录页面
def login(request):
    if request.method=='GET':
        con_style = ConStyle.objects.all()
        data={
            'con_style':con_style,
        }
        return render(request,'login.html',context=data)
    else:
        uname=request.POST.get('uname',None)
        upwd=request.POST.get('upwd',None)
        if uname and upwd:
            user=User.objects.filter(uname=uname).first()
            if user and user.upwd==upwd:
                resp=HttpResponseRedirect(redirect_to='/app/content/wangzhe/1/')
                utoken=uuid.uuid4()
                # 使用session存储会话信息
                resp.set_cookie('utoken',utoken)
                # 将生成的utoken保存在数据库中
                user.utoken=utoken
                user.save()
                # resp.content='666'
                return resp

            else:
                con_style = ConStyle.objects.all()
                data={
                    'msg':'账号或者密码错误，请重新输入',
                    'con_style':con_style
                }
                return render(request,'login.html',context=data)


# 退出登录
def outlogin(request):
    resp=HttpResponseRedirect(redirect_to='/')
    # 勒令客户端删除保存的utoken
    resp.delete_cookie('utoken')

    return resp

# 个人中心
def mine(request):
    utoken=request.COOKIES.get('utoken',None)
    user=User.objects.filter(utoken=utoken).first()
    if utoken:
        uname=user.uname
        uicon='../static/uploads/'+str(user.uicon)
        data={
        'uname':uname,
        'uicon':uicon
    }
        return render(request,'mine.html',context=data)
    else:
        return redirect(reverse('app:login'))


# 获得随机rgb（100,200）颜色数组
def color():
    red = random.randint(100, 220)
    green = random.randint(100, 220)
    black = random.randint(100, 220)
    return (red, green, black)
# 内容
def content(request,con_type,pagenum):
    con_style=ConStyle.objects.all()
    con=Content.objects.filter(con_type=con_type)
    utoken = request.COOKIES.get('utoken', None)
    # 标题的分类
    c_type=ConStyle.objects.filter(s_ename=con_type).first().s_name
    # 设置分页符,每页10条内容
    paginator=Paginator(con,10)
    page=paginator.page(pagenum)

    if utoken:
        uname=User.objects.filter(utoken=utoken).first().uname
        out='退出'
        data={
            'page':page,
            'pagerange':paginator.page_range,
            'currentpage':page.number,
            'utoken':utoken,
            'con_style':con_style,
            'uname':uname,
            'c_type':c_type,
            'out':out,
            'con_type':con_type,
            'color':color()
        }
        return render(request, 'content.html', context=data)
    else:
        out=''
        data = {
            'page':page,
            'pagerange':paginator.page_range,
            'currentpage':page.number,
            'utoken':utoken,
            'con_style':con_style,
            'uname':'登录',
            'c_type':c_type,
            'out':out,
            'con_type':con_type,
            'color':color()
            }
        return render(request, 'content.html', context=data)


def write(request,con_type):
    if request.method=='GET':
        urls = ['http://ossweb-img.qq.com/images/lol/web201310/skin/big86000.jpg',
                'http://ossweb-img.qq.com/images/lol/web201310/skin/big105000.jpg',
                ]
        imgurl = random.sample(urls, 1)[0]
        msg='title'
        data = {
            'con_type': con_type,
            'url': imgurl,
            'msg':msg
        }
        return render(request,'./edit/write.html',context=data)
    else:

        # 重定向到该con_type的内容展示区
        res=HttpResponseRedirect('/app/content/'+con_type+'/1/')
        # 从前端获取输入的title
        title=request.POST.get('title',None)
        # 从前端获取输入的text
        text=request.POST.get('text',None)
        # 获取登入用户的utoken
        utoken=request.COOKIES.get('utoken',None)
        # 根据utoken获取用户名
        uname=User.objects.filter(utoken=utoken).first().uname
        istitle = Content.objects.filter(title=title)
        if title and text and not istitle:
            data=Content()
            data.title=title
            data.text=text
            data.con_type=con_type
            data.uname=uname
            data.save()
            return res
        else:
            urls = ['http://ossweb-img.qq.com/images/lol/web201310/skin/big86000.jpg',
                    'http://ossweb-img.qq.com/images/lol/web201310/skin/big105000.jpg',
                    ]
            imgurl = random.sample(urls, 1)[0]
            msg='标题已经存在，请重新输入。。。。'
            data={
                'msg':msg,
                'url':imgurl
            }
            return render(request,'./edit/write.html',context=data)










